package com.parachutes.aspbillcore.controller;

import com.alipay.api.AlipayApiException;

import com.alipay.api.AlipayConfig;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.parachutes.aspbillapi.domain.BusOrder;
import com.parachutes.aspbillapi.domain.Result;
import com.parachutes.aspbillapi.service.BusOrderService;
import com.parachutes.aspbillapi.service.PaymentService;
import com.parachutes.aspsystemapi.feign.SysUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 支付控制器
 *
 * @author machi
 * @date 2025/02/09
 */
@RestController
public class PaymentController {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    BusOrderService busOrderService;
    @Autowired
    PaymentService paymentService;

    @Autowired
    SysUserServiceFeign sysUserServiceFeign;


    /**
     * 订单支付接口， 核心是调用支付宝的 Factory.Payment.Page().pay() 方法
     *
     * @return
     */
    @PostMapping("/pay")
    public Result pay(@RequestBody BusOrder busOrder) throws AlipayApiException {
        return paymentService.pay(busOrder);
    }


    /**
     * 支付回调接口，如果支付成功，支付宝将会请求此接口，将成功信息返回
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) throws Exception {
        String tradeStatus = request.getParameter("trade_status");

        if (tradeStatus.trim().equals("TRADE_SUCCESS")) {
            Map<String, String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name : parameterMap.keySet()) {
                param.put(name, request.getParameter(name));
            }

            // 验证请求的有效性
            if (Factory.Payment.Common().verifyNotify(param)) {
                System.out.println("通过支付宝的验证");
                String orderIdStr = param.get("out_trade_no");

                BusOrder busOrder = busOrderService.getOne(Wrappers.lambdaQuery(BusOrder.class)
                        .eq(BusOrder::getOutTradeNo, orderIdStr));
                if (busOrder != null) {
                  busOrder.setStatus("1");
                  busOrderService.updateById(busOrder);
                }
                System.out.println("orderIdStr = " + orderIdStr);
            }else {
                System.out.println("支付验证不通过");
            }
        }
        return "success";
    }

    @GetMapping("/query-order")
    public String query(String outTradeNo) throws Exception {
        try {
            // 查询订单状态
            AlipayTradeQueryResponse response = Factory.Payment.Common()
                    .query(outTradeNo); // 订单号（out_trade_no）

            // 处理查询结果
            if ("10000".equals(response.getCode())) {
                System.out.println("查询成功: " + response.getBody());
                System.out.println("订单状态: " + response.getTradeStatus());
            } else {
                System.out.println("查询失败: " + response.getSubMsg());
            }
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }
//    config.protocol = "https";  //协议
//    config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";    //支付宝网关
//    config.signType = "RSA2";   //签名方式
//
//    // 业务配置
//    config.appId = "9021000143641216";
//    config.merchantPrivateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCc1hmJzQ4w0XN8PldUpqQnmUypQKqNJOneokiW8URepkEoZ1bGjCJVj1p2kLukHQyXwfW7NEPh80QruHAwwRRgD2s/h7GPNTBdz9fMgasgTBPe4gqTVzamth8C2z0wqJl8bwqIpjSUUrZncQin8Ki1Je8ssJ9ef8DJuIbrJi/+ibSgcePSPuhKenC98Xfj2MkttUsaDFGUcWDjXeeMvnjV6VahwBkY6yWvHEnJ1T5kIKXXw6fedZeUUGiBifpTfkz+jBmEj11oq0lxnt48IC5HLJ/0cnJKmZCa/KKP6/Tf92EjHp52u4x/osxn7dyXWJ5faAtXoghP84W3V1IVTa35AgMBAAECggEAewz0Do0G9EBxJmrXJAB2zObXIfgtl/39TALxhxQWu1gfyS6DA9ZQ3eZSaLIXtqRgC/VO8ikIlY/Czbawt1/Vt6SBVeAF7MEjiIcY3khiVj26XWXmPEHyDAzZ+ei/cpzlh56rmhklK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TVyw==";
//    config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxdC4nvPRbH5r+IinsZZx8SvaBBHe0Y8Ggk7aZDDZsmWPjVfkTn1P1tLEKoRaUcBjH9E6VBQbbUlTFpkkYhtzqV6rq7phJrueR6dDCaqar4B0LnQvC9cs+A7SeBZigdZ5z76DADegOlkrM3XHUQcGvBHeBj9XwNWwOY/G9THTrbPCWxeJE1XzhBM4cJra4Siy2m7jN9X46JxEb4H5/Z+G8oeNZEgMxF2KdTcUEYN8ouvACrNNPYYWy1rkTa7slTuUmUjp5YZ3QR1eiIrnw74LVWXQrUoS5mC2OiYCLkPYtfgMIfC9UASKsVTE4XZCbI8RSz0+5QhJcoqOdeyfllStJwIDAQAB";
//    config.notifyUrl = "https://0354-223-104-68-72.ngrok-free.app/bill/notify";

    @PostMapping("/transfer")
    public Result transfer(@RequestBody BusOrder busOrder) {
        paymentService.transfer(busOrder);
        return Result.of(true, "提现成功", busOrder);
    }

}